package com.playball.lottery.frm.yhzx;


import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.nt.GetJsonData;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.AbstractActivity;
import com.playball.lottery.util.AppUtils;
import com.playball.lottery.util.Constants;
import com.playball.lottery.util.ShenzhoufuUtil;

/***
 * 神州付
 * 
 * @ClassName: ShenzhoufuActivity
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author vanszhen
 * @date 2014年8月22日 上午11:23:25
 * 
 */
public class ShenzhoufuActivity extends AbstractActivity implements OnClickListener {

	/** 返回 */
	private TextView txtBack;
	/** 标题 */
	private TextView txtTitle;

	/** 卡面值 10 --- 50 的 RadioGroup */
	private RadioGroup radioGroup01;
	/** 卡面值 100 --- 500 的 RadioGroup */
	private RadioGroup radioGroup02;
	/** 判断点击 是 哪个RadioGroup */
	private Boolean changeedGroup = false;
	/** 卡的面值 */
	private String cardValueStr;
	
	/**充值卡卡号*/
	private EditText edtPhoneNum ;
	/**充值卡密码*/
	private EditText edtPhonePwd ;
	/**实际到账的钱*/
	private TextView txtActualMoney ;
	/**显示输入多少个*/
	private TextView txtShowLength;
	
	/**立即支付*/ 
	private Button btnNowRech ;
	
	/**用户的id*/
	private String UserID ;
	/**类型*/
	private String typeBankPay = "shenzhoufu_mobile";
	
	/**szf */
	private ShenzhoufuUtil szfUtil ;
	/**钱*/
	private String money = ""; 
	
	private String sn ;
	
	private String password ;

	
	private float dbActMoney ; 
	
	
	@Override 
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.jdd_shenzhoufu_main);
		initView();
	}

	// 初始化布局
	private void initView() {
		txtBack = (TextView) findViewById(R.id.top_title_back);
		txtBack.setOnClickListener(this);
		txtTitle = (TextView) findViewById(R.id.top_title_info);
		txtTitle.setText("手机卡充值");
		
		radioGroup01 = (RadioGroup) findViewById(R.id.radi_group_01);
		radioGroup02 = (RadioGroup) findViewById(R.id.radi_group_02);
		
		edtPhoneNum = (EditText) findViewById(R.id.edt_phon_num);
		edtPhonePwd = (EditText) findViewById(R.id.edt_phon_pwd);
		
		txtShowLength = (TextView) findViewById(R.id.tv_show_num_hint);
		txtShowLength.setText(Html.fromHtml( "已输入" +"<font color=#fe5052>" + 0 + "</font>" + "位"));
		
		txtActualMoney = (TextView) findViewById(R.id.tv_show_actual_money_left);
		
		btnNowRech = (Button) findViewById(R.id.btn_now_rech);
		btnNowRech.setOnClickListener(this);
		radioGroup01.setOnCheckedChangeListener(new MyRadioGroupOnCheckedChangedListener() );
		radioGroup02.setOnCheckedChangeListener(new MyRadioGroupOnCheckedChangedListener() );
		
		szfUtil = new ShenzhoufuUtil();
		
		//监听
		edtPhoneNum.addTextChangedListener(new TextWatcher() {
			private boolean isChanged = false;
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if(isChanged){
		            return ;
		        }
				if (!AppUtils.isBlank(edtPhoneNum.getText().toString().trim())) {
					isChanged = true;
					txtShowLength.setText(Html.fromHtml( "已输入" +"<font color=#fe5052>" + edtPhoneNum.length() + "</font>" + "位"));
					 isChanged = false;
					 edtPhoneNum.invalidate();
				}else {
					txtShowLength.setText(Html.fromHtml( "已输入" +"<font color=#fe5052>" + 0 + "</font>" + "位"));
				}
				
				
			}
		});
	}

	//判断 group
	class MyRadioGroupOnCheckedChangedListener implements OnCheckedChangeListener {
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			if (!changeedGroup) {
				changeedGroup = true ;
				if (group == radioGroup01) {
					radioGroup02.clearCheck();
					int radoBntId = radioGroup01.getCheckedRadioButtonId() ;
					RadioButton rButton = (RadioButton) findViewById(radoBntId);
					cardValueStr = rButton.getText().toString();
					showMoney(cardValueStr);
				}else if (group == radioGroup02) {
					radioGroup01.clearCheck();
					int radoBntId = radioGroup02.getCheckedRadioButtonId() ;
					RadioButton rButton = (RadioButton) findViewById(radoBntId);
					cardValueStr = rButton.getText().toString();
					showMoney(cardValueStr);
				}
				  changeedGroup = false;
			}
		}
	};
	
	//实际到账
	private void showMoney(String cardValueStr ){
		dbActMoney = (float) (Integer.parseInt(convertCardValue(cardValueStr)) * (1 - 0.03)) ;
		txtActualMoney.setText(Html.fromHtml( "<font color=#fe5052>" + dbActMoney + "</font>" + "元"));
	}
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.top_title_back:
			Intent data=new Intent(); 
			data.putExtra("szfcancle", "用户取消支付");
			setResult(Constants.ZNZH_RES_CODE, data);
			ShenzhoufuActivity.this.finish();
			break;
		//充值
		case R.id.btn_now_rech:
			checkAndPay();
			break;
		default:
			break;
		}

	}
	
	//转换
	private String convertCardValue (String cardValueStr){
		String moneyStr = "" ;
		moneyStr = cardValueStr.split("元")[0];
		Log.d("van", moneyStr);
		return moneyStr ;
		
	}
	
	private void checkAndPay() {
		
		if (AppUtils.isBlank(cardValueStr)) {
			showToast("请选择卡的面值");
			return  ;
		}else {
			money =	convertCardValue(cardValueStr);
		}
		//充值卡的卡号
		if (AppUtils.isBlank(edtPhoneNum.getText().toString().trim())) {
			showToast("请输入您的充值卡的卡号");
			return  ;
		}
		//充值卡的卡号
		if (AppUtils.isBlank(edtPhonePwd.getText().toString().trim())) {
			showToast("请输入您的充值卡的密码");
			return  ;
		}
		sn = edtPhoneNum.getText().toString().trim() ;
		password = edtPhonePwd.getText().toString().trim() ;
		UserID = ApplicationData.getInstance().getUserID();
		// 扣除 手续费
		AsyncLoader task = new AsyncLoader(typeBankPay, Float.toString(dbActMoney));
		task.execute("108");
		
	}


	/**
	 * 异步请求、
	 * 交易号  要扣除 手续费
	 */
	   private ShowTipDialog showdialog = new ShowTipDialog();
		// 调用奖天彩的接口
		public class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask
			
			private String typeBankPay;
			private String money;
			
			public AsyncLoader(String typeBankPay, String money) {
				super();
				this.typeBankPay = typeBankPay;
				this.money = money;
			}
			protected void onPreExecute() {
				showdialog.showDialog(context);
			}
			@Override
			protected String doInBackground(String... params) {
				String strResult;
				try {
					// 设置请求所需参数
					JSONObject param = new JSONObject();
					param.put("BankPay", typeBankPay);
					param.put("PayMoney", money);
					// 设置请求action
					String action = params[0];
					strResult = GetRequestParams.getRequestUserIDResult(param.toString(), UserID, action, getApplicationContext());
					return strResult;
				} catch (Exception ex) {
					Log.e("error", ex.toString());
					return null;
				}
			}

			protected void onPostExecute(String result) {
				if (result != null) {
					try {
						JSONTokener jsonParser = new JSONTokener(result);
						JSONObject js = (JSONObject) jsonParser.nextValue();
						if (Integer.parseInt(js.getString("Code")) == 0) {
						String	ordernum = js.getString("Data");
						Log.d("van", ordernum);
						szf(ordernum);
						} else {
							String tip = js.getString("Data");
							if(!TextUtils.isEmpty(tip)) {
								if(tip.length() == 38) {
									tip = tip.substring(0, 30);
								}
							}
							Toast.makeText(context, tip, Toast.LENGTH_LONG).show();
						}
						showdialog.closeDialog();
					} catch (JSONException ex) {
						// 异常处理代码
						Log.e("error", ex.toString());
						Toast.makeText(context, R.string.top_up_failure, Toast.LENGTH_SHORT).show();
					} finally {
						showdialog.closeDialog();
					}
				} else {
					Toast.makeText(context, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
				}
			}
			 
		}
		
		private void szf(String orderId){
		    String getCardTypeCombine  = szfUtil.getCardTypeCombine(sn);
			String url = szfUtil.urlRequestData(orderId, getCardTypeCombine, UserID, money, sn, password) ;
			AsynSZFcLoader loader = new AsynSZFcLoader();
			loader.execute(url);
		}
		//神州付
		class AsynSZFcLoader extends AsyncTask<String, Integer, String> {
			
			@Override
			protected String doInBackground(String... params) {
				String url =  params[0] ;
				String code  =  "" ;
				try {
					code = 	GetJsonData.getContent(url);
					Log.d("van", code);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return code;
			}
			
			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				String code   =  result.replaceAll("\n", "");
				String codeShow = szfUtil.codeShowTip(code);
				if (code.equals("200") || code.equals("105")) {
					Intent data=new Intent(context, ShenzhoufuSuccessActivity.class); 
					data.putExtra("szfcancle", codeShow);
					startActivityForResult(data, 10001);
					setResult(20008);
				}else {
					Intent data=new Intent(); 
					data.putExtra("szfcancle", codeShow);
					setResult(Constants.ZNZH_RES_CODE, data);
				}
				ShenzhoufuActivity.this.finish();
			}
			
		} 
		
 
}
